<template>
  <div class="content" v-loading="loading">
    <div class="inputLine flexBet">
      <div class="flex">
        <el-input
          :disabled="!isSortable"
          style="width: 320px"
          @input="getList"
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>

      <div class="flex">
        <div
          class="sort"
          @click="handelSort"
          v-if="isLeader & (fileList.length > 0)"
        >
          {{ isSortable ? '排序' : '保存' }}
        </div>
        <div
          class="sort"
          style="margin-left: 15px"
          v-if="isLeader && fileList.length > 0 && !isSortable"
          @click="handelcancel"
        >
          取消
        </div>
        <div class="upload" @click="handelUpload" v-if="isSortable">上传</div>
        <input
          style="display: none"
          class="uploadContain_input"
          type="file"
          accept=".gif, .png, .jpeg,  .jpg,  .mp4, .webm, .pdf, .docx, .doc, .rtf, .pptx, .ppt,  .xls, .xlsx ,.wps ,.ofd
        ,.txt ,.js ,.json ,.css ,.sql ,.xml ,.java ,.cs(c#)"
          ref="fileInput"
          @change="uploadFile($event)"
          multiple
        />
      </div>
    </div>
    <div class="tip">{{ !isSortable ? '注：可通过拖拽来调整排序' : '' }}</div>
    <draggable
      v-if="fileList.length > 0"
      :options="{ disabled: isSortable }"
      class="box"
      v-model="fileList"
      @end="onDragEnd"
    >
      <div
        class="file shou flexColCenter rela"
        @click="openfile(item.fileUrl, item.fileName)"
        v-for="(item, index) in fileList"
        :key="index"
      >
        <!-- 名字部分 -->

        <img class="icon" :src="returnIcon(item.fileUrl, 1)" alt=""/>

        <el-input
          ref="input"
          @focus.stop=""
          @click.stop.native=""
          @blur="renameBlur($event, item, index)"
          v-if="item.edit"
          class="filename"
          type="text"
          v-model="item.fileName"
          style="max-width: calc(100% - 639px)"
          size="mini"
        ></el-input>

        <div
          v-if="!item.edit"
          class="filename flexColCenter"
          style="max-width: calc(100% - 639px)"
        >
          <tooltip :text="item.fileName" width="100%"></tooltip>
        </div>
        <div class="type" v-if="!item.edit">{{ item.extension }}</div>

        <img
          v-if="!item.edit && isSortable"
          @click.stop="handelRename(item, index)"
          :style="{ opacity: item.edit ? 0 : 1 }"
          class="edit shou"
          src="@/assets/images/disciplineGroup/greenEdit.png"
          alt=""
        />

        <!-- 尾部 -->
        <div class="flexColCenter absolute" style="right: 0; padding-right: 143px">
          <div class="uploadUser">{{ item.createByName }}</div>
          <div class="time">{{ parseTime(item.createTime) }}</div>
        </div>
      </div>
    </draggable>
    <div
      style="width: 100%; height: 100%"
      v-if="fileList.length == 0"
      class="flexCen flexColCenter"
    >
      <el-empty description="暂无资料~"></el-empty>
    </div>
    <fileDrawer
      :show.sync="drawer"
      :url="drawerurl"
      :name="drawername"
      :type="drawertype"
      :isHttps="isHttps"
    ></fileDrawer>
  </div>
</template>

<script>
import fileDrawer from '@/components/fileDrawer.vue'
import { uploadOSS } from '@/api/upload'
import draggable from 'vuedraggable'
import {
  branchDisciplineFileList,
  addFile,
  editFile,
  sortFile
} from '@/api/disciplineGroup/disciplineGroup'
import { returnIcon } from '@/utils/util.js'

export default {
  components: { draggable, fileDrawer },
  props: {
    activeIndex: [Number, String],
    disciplineGroupId: [Number, String],
    isLeader: Boolean
  },
  data() {
    return {
      isHttps: false,
      drawer: false,
      drawerurl: '',
      drawername: '',
      drawertype: '',
      returnIcon: function(url, type) {
        return returnIcon(url, type)
      },
      isSortable: true,
      queryParams: {
        fileName: ''
      },
      loading: false,
      fileList: [],
      initList: []
    }
  },
  watch: {
    isSortable() {
      this.$emit('updateSorting', !this.isSortable)
    },
    activeIndex: {
      async handler(val) {
        if (val == 2) {
          this.getList()
        }
      },
      immediate: true
    },
    disciplineGroupId() {
      if (this.activeIndex == 2) {
        this.getList()
      }
    }
  },
  methods: {
    openfile(url, name) {
      let uploadType = url
        .slice(url.lastIndexOf('.'), url.length)
        .toLowerCase()
      let arr = [
        '.gif',
        '.png',
        '.jpeg',
        '.jpg',
        '.mp4',
        '.webm',
        '.pdf',
        '.wps',
        '.docx',
        '.doc',
        '.rtf',
        '.pptx',
        '.ppt',
        '.xls',
        '.xlsx',
        '.wps',
        '.ofd',
        '.txt',
        '.js',
        '.json',
        '.css',
        '.sql',
        '.xml',
        '.java',
        '.cs(c#)'
      ]
      if (arr.indexOf(uploadType) > -1) {
        this.drawer = true
        this.drawerurl = url
        this.drawername = name
        this.drawertype = 1
      } else {
        window.open(url, '_blank')
      }
    },
    // 取消排序
    handelcancel() {
      this.fileList = this.initList
      this.isSortable = !this.isSortable
      this.$message({
        type: 'success',
        message: '取消排序'
      })
    },

    /**
     * 获取文件名的基础部分（去掉编号）
     */
    getBaseFileName(fileName) {
      return fileName.replace(/\(\d+\)(?=\.[^.]+$)|\(\d+\)/, '')
    },

    /**
     * 从文件名中提取编号
     */
    getFileNumber(fileName) {
      const match = fileName.match(/\((\d+)\)/)
      return match ? parseInt(match[1], 10) : 0
    },

    generateUniqueFileName(fileList, newName, excludeIndex) {
      // 检查用户是否明确指定了编号
      const userSpecifiedNumberMatch = newName.match(/\((\d+)\)/)
      const hasUserSpecifiedNumber = userSpecifiedNumberMatch !== null
      const userSpecifiedNumber = hasUserSpecifiedNumber
        ? parseInt(userSpecifiedNumberMatch[1])
        : null

      // 获取基础文件名（去掉编号）
      const baseName = this.getBaseFileName(newName)
      const lastDotIndex = baseName.lastIndexOf('.')
      const nameWithoutExt = baseName.slice(0, lastDotIndex)
      const ext = baseName.slice(lastDotIndex)

      // 获取所有同名文件（排除当前文件）
      const sameNameFiles = fileList.filter((file, fileIndex) => {
        if (fileIndex === excludeIndex) return false
        return (
          this.getBaseFileName(file.fileName + file.extension) === baseName
        )
      })

      // 如果没有同名文件，直接返回用户指定的名称
      if (sameNameFiles.length === 0) {
        return newName
      }

      // 如果用户明确指定了编号
      if (hasUserSpecifiedNumber) {
        // 检查指定的编号是否已被占用（排除当前文件）
        const isNumberTaken = fileList.some((file, index) => {
          if (index === excludeIndex) return false
          const currentNumber = this.getFileNumber(
            file.fileName + file.extension
          )
          return (
            currentNumber === userSpecifiedNumber &&
            this.getBaseFileName(file.fileName + file.extension) === baseName
          )
        })

        // 如果编号未被占用，使用用户指定的名称
        if (!isNumberTaken) {
          return newName
        }
        // 如果编号已被占用，继续下面的自动编号逻辑
      }

      // 自动编号逻辑
      const existingNumbers = sameNameFiles
        .map((file) => {
          return this.getFileNumber(file.fileName + file.extension)
        })
        .filter((num) => num !== 0) // 排除无编号的文件

      // 找出可用的最小编号
      let nextNumber = 1
      while (existingNumbers.includes(nextNumber)) {
        nextNumber++
      }

      // 返回自动编号后的文件名
      return `${nameWithoutExt.replace(/\(\d+\)$/, '')}(${nextNumber})${ext}`
    },
    // 重命名确认
    async renameBlur(e, item, index) {
      try {
        // 生成不重复的文件名
        const uniqueName = this.generateUniqueFileName(
          this.fileList,
          item.fileName + item.extension,
          index
        )

        // 更新文件名
        const lastDotIndex = uniqueName.lastIndexOf('.')
        this.fileList[index].fileName = uniqueName.slice(0, lastDotIndex)
        this.fileList[index].extension = uniqueName.slice(lastDotIndex)

        // 触发视图更新
        this.$set(this.fileList, index, this.fileList[index])

        this.$emit('loading', true)
        let res = await editFile({
          fileId: item.fileId,
          fileName: this.fileList[index].fileName + item.extension
        })
        if (res.code == 200) {
          this.$modal.msgSuccess('修改成功')
          item.edit = false
          this.initList = this.fileList
          this.$forceUpdate()
        }
      } finally {
        this.$emit('loading', false)
      }
    },
    // 重命名操作
    handelRename(item, index) {
      this.fileList.map((item) => {
        item.edit = false
      })
      this.fileList[index].edit = true
      this.$set(this.fileList, index, this.fileList[index])

      this.$nextTick(() => {
        this.$refs.input[0].focus()
      })
    },
    // 上传操作
    handelUpload() {
      this.$refs.fileInput.click()
    },
    // 上传确认
    async uploadFile(event) {
      let files = event.target.files
      let formData = new FormData()
      let names = []
      for (let i = 0; i < Array.from(files).length; i++) {
        // 生成不重复的文件名
        const uniqueName = this.generateUniqueFileName(
          this.initList,
          Array.from(files)[i].name,
          -1
        )
        names.push(uniqueName)
        formData.append(
          'files',
          new File([Array.from(files)[i]], Array.from(files)[i].name)
        )
      }
      let res = await uploadOSS(
        files,
        `${this.$store.getters.schoolId}/disciplineGroup/${this.disciplineGroupId}`,
        true,
        event
      )
      event.target.value = ''
      console.log(res)
      let data = res.map((item, index) => {
        return {
          fileName: names[index],
          fileUrl: item.url,
          disciplineGroupId: this.disciplineGroupId
        }
      })
      let loading
      try {
        loading = this.$loading({
          lock: true,
          text: '上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)'
        })
        let res = await addFile({ disciplineGroupFileList: data })
        if (res.code == 200) {
          this.getList()
          this.$modal.msgSuccess('上传成功')
        }
      } finally {
        loading.close()
      }
    },
    // 排序确认
    async handelSort() {
      // 要保存的时候
      if (!this.isSortable) {
        try {
          this.$emit('loading', true)
          let res = await sortFile({
            disciplineGroupId: this.disciplineGroupId,
            fileSort: this.fileList
              .map((item) => {
                return item.fileId
              })
              .join(',')
          })
          if (res.code == 200) {
            this.isSortable = !this.isSortable
            this.initList = this.fileList
            this.$message({
              type: 'success',
              message: '排序成功'
            })
          }
        } finally {
          this.$emit('loading', false)
        }
      } else {
        this.isSortable = !this.isSortable
      }
    },
    onDragEnd() {
      console.log(this.courseList)
    },

    async getList() {
      this.$emit('loading', true)
      try {
        const res = await branchDisciplineFileList({
          disciplineGroupId: this.disciplineGroupId,
          fileName: this.queryParams.fileName
        })
        if (res.code == 200) {
          this.fileList = res.data
          this.fileList.map((item) => {
            const lastDotIndex = item.fileName.lastIndexOf('.')
            const name = item.fileName.slice(0, lastDotIndex) // 文件名部分
            const extension = item.fileName.slice(lastDotIndex) // 扩展名部分（包括点号）
            item.fileName = name
            item.extension = extension
            item.edit = false
          })
          this.initList = this.fileList
        }
      } finally {
        this.$emit('loading', false)
      }
    }
  }
}
</script>

<style scoped lang="scss">
@mixin btn_plain($bg_color, $color) {
  background: $bg_color;
  color: $color;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  user-select: none;

  &:active {
    background: darken($bg_color, 5%);
    color: darken($color, 18%);
  }

  &:disabled {
    background: lighten($bg_color, 5%);
    color: lighten($color, 40%);
  }

  @content;
}

.upload {
  @include btn_plain(#28b28b, #ffffff) {
    margin-left: 15px;
    width: 80px;
    height: 40px;
    box-sizing: border-box;
    border-radius: 8px;
    border: 1px solid #edeff0;

    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
  }
}

.sort {
  @include btn_plain(#ffffff, #28b28b) {
    width: 80px;
    height: 40px;
    box-sizing: border-box;
    border-radius: 8px;
    border: 1px solid #edeff0;

    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
  }
}

.content {
  height: calc(100vh - 310px + 120px);
  display: flex;
  box-sizing: border-box;
  flex-direction: column;

  .inputLine {
    height: 64px !important;
    box-sizing: border-box;
    padding: 24px 34px 0 19px;
  }

  .tip {
    font-size: 12px;
    color: rgb(255, 156, 34);
    height: 20px;
    line-height: 20px;
    margin: 2px 0 2px 19px;
  }

  .box {
    margin: 0 0 0 0;
    padding: 0 0 0 19px;
    width: 100%;
    height: calc(100vh - 310px + 120px - 64px);
    overflow-y: auto;

    .file:hover,
    .file:focus {
      background: #f5f6f7;
    }

    .file {
      box-sizing: border-box;
      width: 100%;
      padding: 0 0 0 10px;
      margin-bottom: 8px;
      height: 48px;

      .icon {
        width: 32px;
        height: 32px;
      }

      .edit {
        margin-left: 20px;
        width: 16px;
        height: 16px;
      }

      .filename {
        margin-left: 16px;
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 16px;
        color: #333333;
        line-height: 22px;
        text-align: left;
        font-style: normal;
      }

      .type {
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 16px;
        color: #333333;
        line-height: 22px;
        text-align: left;
        font-style: normal;
      }

      .uploadUser {
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 16px;
        color: #999999;
        line-height: 22px;
        text-align: left;
        font-style: normal;
      }

      .time {
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 16px;
        color: #999999;
        line-height: 22px;
        text-align: left;
        font-style: normal;
        margin-left: 130px;
      }
    }
  }
}
</style>
